<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input v-model="keywords" prefix-icon="Search" style="width: 240px; margin-right: 10px" placeholder="请输入起始或结束地点查询"></el-input>
      <el-button type="info" plain @click="load">查询</el-button>
      <el-button type="warning" plain style="margin: 0 10px" @click="reset">重置</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px">
      <el-table stripe :data="orderList">
        <el-table-column prop="id" label="订单编号" />
        <el-table-column prop="username" label="用户名称" />
        <el-table-column prop="team_name" label="团队名称" />
        <el-table-column prop="team_img" label="团队图片">
          <template v-slot="scope">
            <el-image style="width: 100px; height: 100px; display: block" v-if="scope.row.team_img"
                      :src="scope.row.team_img" :preview-src-list="[scope.row.team_img]" preview-teleported></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="team_type_name" label="类型名称" />
        <el-table-column prop="create_time" label="创建时间">
          <template v-slot="scope">
            {{dayjs(scope.row.create_time).format('YYYY-MM-DD HH:mm:ss')}}
          </template>
        </el-table-column>
        <el-table-column prop="start_location" label="开始地点" />
        <el-table-column prop="end_location" label="结束地点" />
        <el-table-column prop="start_time" label="预约时间">
          <template v-slot="scope">
            {{dayjs(scope.row.start_time).format('YYYY-MM-DD HH:mm:ss')}}
          </template>
        </el-table-column>
        <el-table-column prop="money" label="金额" />
        <el-table-column prop="status" label="订单状态">
          <template v-slot="scope">
            <div v-if="scope.row.status===0"><el-tag type="success">{{"用户已支付"}}</el-tag></div>
            <div v-if="scope.row.status===1"><el-tag type="primary">{{"商家已接单"}}</el-tag></div>
            <div v-if="scope.row.status===2"><el-tag type="success">{{"服务已完成"}}</el-tag></div>
            <div v-if="scope.row.status===3"><el-tag type="warning">{{"用户已取消"}}</el-tag></div>
            <div v-if="scope.row.status===4"><el-tag type="danger">{{"商家拒绝接单"}}</el-tag></div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template v-slot="scope">
            <div style="display: flex; justify-content: flex-start; align-items: center;">
              <el-button
                  plain
                  v-if="scope.row.status === 0"
                  type="success"
                  @click="acceptOrder(scope.row.id)">
                接单
              </el-button>
              <el-button
                  plain
                  v-if="scope.row.status === 0"
                  type="danger"
                  @click="rejectOrder(scope.row.id)">
                拒绝接单
              </el-button>
              <el-button
                  plain
                  v-if="scope.row.status === 1"
                  type="primary"
                  @click="completeService(scope.row.id)">
                服务完成
              </el-button>
              <el-button type="danger" circle :icon="Delete" @click="del(scope.row.id)" style="margin-right: 5px;"></el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="card">
      <el-pagination :total="total" v-model:current-page="pagination.currentPage" :page-size="pagination.pageSize" @current-change="load" />
    </div>

    <el-dialog title="订单信息" v-model="formVisible" width="50%" destroy-on-close>
      <el-form :model="form" label-width="70px" style="padding: 20px">
        <el-form-item prop="content" label="评价内容">
          <el-input v-model="form.value.content" type="textarea" disabled :rows="3"></el-input>
        </el-form-item>
        <el-form-item prop="answer" label="回复内容">
          <el-input v-model="form.value.answer" type="textarea" :rows="3"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="内容" v-model="viewVisible" width="50%" :close-on-click-modal="false" destroy-on-close>
      <div class="editor-content-view" style="padding: 20px" v-html="formContent"></div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="viewVisible = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import {ElMessage, ElMessageBox, ElNotification} from "element-plus";
import { Delete } from "@element-plus/icons-vue";
import { takeAccessToken } from "@/net/index.js";
import { get, post } from "@/net/index.js";
import dayjs from "dayjs";

const baseUrl = import.meta.env.VITE_BASE_URL;

const pagination = reactive({
  pageSize: 3,
  currentPage: 1,
  total: 0
});

const keywords = ref("");
let token = null;
const form = reactive({});
const formContent = ref();
const formVisible = ref(false);
const viewVisible = ref(false);
const total = ref();
const orderList = ref([]);

const load = () => {
  const userInfo = JSON.parse(localStorage.getItem('user'));
  const teamId = userInfo.team_leader_id;
  get(`/api/order/getOrderListByTeamId/${pagination.currentPage}?keywords=${keywords.value || ''}&teamId=${teamId}`, (res) => {
    total.value = res.total;
    orderList.value = res.list;
    console.log(orderList.value)
  }, (err) => {
    ElMessage.warning("请求失败");
    console.log(err);
  });
};


const reset = () => {
  keywords.value = ''
  load()
}

const acceptOrder = (id) => {
  ElMessageBox.confirm('您确定要接单吗？', '接单确认', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(() => {
    post(`/api/order/acceptOrder/${id}`, null, (res) => {
      ElNotification({
        title: '成功',
        message: '接单成功',
        type: 'success',
        duration: 1000,
        position: 'top-right'
      });
      load(); // 刷新订单列表
    }, (err) => {
      ElMessage.error("接单失败");
      console.log(err);
    });
  }).catch(err => {
    console.error(err);
  });
};


const rejectOrder = (id) => {
  ElMessageBox.confirm('您确定要拒绝接单吗？', '拒绝确认', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(() => {
    post(`/api/order/rejectOrder/${id}`, null, (res) => {
      ElNotification({
        title: '成功',
        message: '已拒绝接单',
        type: 'success',
        duration: 1000,
        position: 'top-right'
      });
      load(); // 刷新订单列表
    }, (err) => {
      ElMessage.error("拒绝接单失败");
      console.log(err);
    });
  }).catch(err => {
    console.error(err);
  });
};

const completeService = (id) => {
  ElMessageBox.confirm('您确定服务已完成吗？', '完成确认', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(() => {
    post(`/api/order/completeService/${id}`, null, (res) => {
      ElNotification({
        title: '成功',
        message: '服务已完成',
        type: 'success',
        duration: 1000,
        position: 'top-right'
      });
      load(); // 刷新订单列表
    }, (err) => {
      ElMessage.error("服务完成失败");
      console.log(err);
    });
  }).catch(err => {
    console.error(err);
  });
};


const del = (id) => {

  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', { type: 'warning', confirmButtonText: '确认删除',
    cancelButtonText: '取消', }).then(res => {
    post(`/api/order/deleteOrder/${id}`,null,(res)=>{
      ElMessage.success("删除成功");
      load();
    },(err)=>{
      ElMessage.success("删除失败");
    })
  }).catch(err => {
    console.error(err)
  })
}
onMounted(() => {
  load();
  token = { 'Authorization': `Bearer ${takeAccessToken()}` };
});
</script>

<style scoped>
</style>